package com.example.pungolo.journal.view;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

import com.example.pungolo.journal.R;
import com.example.pungolo.journal.U;
import com.example.pungolo.journal.model.DiaryPage;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

public class DiaryPageView extends LinearLayout {
  private TextView dayLabelView;
  private ImageView photoView;
  private ListView diaryEntryContainer;
  private DiaryPage page;
  private View content;
  private final static DateFormat dateFormat = SimpleDateFormat.getDateInstance();
  private OnClickListener onEntryClickedListener;
  private OnClickListener onMyEntryClickedListener;
  private OnClickListener onMyAddEntryClickedListener;
  private OnClickListener onAddEntryClickedListener;
  private OnClickListener onPhotoViewClicked;
  private OnLongClickListener onPhotoViewLongClicked;
  private Bitmap currentBitmap;

  public DiaryPageView(Context context) {
    super(context);
    init();
  }

  public DiaryPageView(Context context, AttributeSet attrs) {
    super(context, attrs);
    init();
  }

  @SuppressLint("NewApi")
  public DiaryPageView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    init();
  }

  private void init() {
    Context context = getContext();

    // Gonfia la view dall'xml!
    View.inflate(context, R.layout.diary_page_view, this);

    this.content = this.getChildAt(0);
    this.dayLabelView = (TextView) findViewById(R.id.day_label);
    this.photoView = (ImageView) findViewById(R.id.photo);
    this.diaryEntryContainer = (ListView) findViewById(R.id.entry_container);
    this.diaryEntryContainer.setAdapter(null);

    this.photoView.setOnClickListener(new OnClickListener() { public void onClick(View v) { photoViewClicked(); } });
    this.photoView.setOnLongClickListener(new OnLongClickListener() { public boolean onLongClick(View v) { return photoViewLongClicked(); } });
    this.onMyEntryClickedListener = new OnClickListener() { public void onClick(View v) { entryClicked((DiaryEntryView) v); } };
    this.onMyAddEntryClickedListener = new OnClickListener() { public void onClick(View v) { addEntryClicked(); } };

    // Finch� non viene impostata una DiaryPage, lascio questa view
    // complemente vuota
    removeAllViews();
  }

  public void setDiaryPage(DiaryPage page) {
    if (page != null) {
      // Riaggiungo il contenuto se prima non c'era una DiaryPage
      if (this.page == null)
        this.addView(this.content);
      dayLabelView.setText(dateFormat.format(U.dateFromDay(page.getDay())));
      DiaryEntryAdapter adapter = new DiaryEntryAdapter();
      adapter.setPage(page);
      if (page.getDay() == U.today()) {
        adapter.hasAddButton = true;
      }
      diaryEntryContainer.setAdapter(adapter);

      String path = page.getImagePath();
      if (path == null) {
        // La foto non esiste, metto quella di default
        photoView.setImageResource(R.drawable.default_photo);
      } else if (new File(path).exists()) {
        // Carica l'immagine nella photoView
        this.photoView.setImageResource(R.drawable.loading_photo);
        
        BitmapWorkerTask task = new BitmapWorkerTask(this, BitmapWorkerTask.screenSize(getContext()), page.getCropRect());
        task.execute(path);
      } else {
        // Il file dell'immagine non esiste, mi sa che è stata cancellata
        photoView.setImageResource(R.drawable.notfound_photo);
      }
    } else {
      diaryEntryContainer.setAdapter(null);
      removeAllViews();
    }
    this.page = page;
  }

  public DiaryPage getDiaryPage() {
    return page;
  }
  
  public ListView getEntryListView() {
    return diaryEntryContainer;
  }
  
  public ImageView getPhotoImageView() {
    return photoView;
  }

  public void setOnEntryClickedListener(OnClickListener onClickListener) {
    this.onEntryClickedListener = onClickListener;
  }
  public void entryClicked(DiaryEntryView v) {
    if (this.onEntryClickedListener != null)
      onEntryClickedListener.onClick(v);
  }
  
  public void setOnAddEntryClickedListener(OnClickListener onClickListener) {
    this.onAddEntryClickedListener = onClickListener;
  }
  public void addEntryClicked() {
    if (this.onAddEntryClickedListener != null)
      onAddEntryClickedListener.onClick(this);
  }
  
  public void setOnPhotoViewClicked(OnClickListener onClickListener) {
    this.onPhotoViewClicked = onClickListener;
  }
  protected void photoViewClicked() {
    if (this.onPhotoViewClicked != null)
      onPhotoViewClicked.onClick(this);
  }
  
  public void setOnPhotoViewLongClicked(OnLongClickListener onClickListener) {
    this.onPhotoViewLongClicked = onClickListener;
  }
  protected boolean photoViewLongClicked() {
    if (this.onPhotoViewLongClicked != null)
      return onPhotoViewLongClicked.onLongClick(this);
    return false;
  }

  public void setImageBitmap(Bitmap bm) {
    if (this.currentBitmap != null)
      this.currentBitmap.recycle();
    this.currentBitmap = bm;
    if (bm != null) {
      this.photoView.setImageBitmap(bm);
    } else {
      this.photoView.setImageResource(R.drawable.error_photo);
    }
  }
  
  private final class DiaryEntryAdapter extends BaseAdapter {
    boolean hasAddButton;
    DiaryPage page;
    public void setPage(DiaryPage page) {
      this.page = page;
      this.notifyDataSetChanged();
    }
    
    public int getCount() {
      return (page == null ? 0 : page.getEntryCount()) + (hasAddButton ? 1 : 0);
    }
    public Object getItem(int position) {
      if (position == page.getEntryCount())
        return null;
      else
       return page.getEntry(position);
    }
    public long getItemId(int position) {
      if (position == page.getEntryCount())
        return -1;
      else
        return page.getEntry(position).getDate().getTime();
    }
    public View getView(int position, View convertView, ViewGroup parent) {
      if (position < page.getEntryCount()) {
        DiaryEntryView view;
        if (convertView != null && convertView instanceof DiaryEntryView) {
          view = (DiaryEntryView) convertView;
        } else {
          view = new DiaryEntryView(getContext());
        }
        view.setOnClickListener(onMyEntryClickedListener);
        view.setEntry(page.getEntry(position));
        return view;
      } else {
        Button view;
        if (convertView != null && convertView instanceof Button) {
          view = (Button) convertView;
        } else {
          view = new Button(getContext());
        }
        view.setOnClickListener(onMyAddEntryClickedListener);
        view.setText(R.string.add_entry);
        return view;
      }
    }
  }
}
